package com.xuecheng.content.controller;

import com.xuecheng.commons.model.vo.CoursePubVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.domain.CoursePub;
import freemarker.template.TemplateException;
import org.springframework.web.bind.annotation.*;
import com.xuecheng.content.service.CoursePubService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程发布前端控制器
 * </p>
 *
 * @author itheima
 */
@Slf4j
@RestController
@RequestMapping("/coursePub")
public class CoursePubController {

    @Autowired
    private CoursePubService  coursePubService;

    @GetMapping("/preview/{courseBaseId}")

    /*
     *   课程预览
     *    返回值：
     *       ModelAndView  数据和页面模型
     *       数据：map
     * */
    public ModelAndView preview(@PathVariable("courseBaseId") Long courseBaseId) {
        ModelAndView view = new ModelAndView();
        //1.指定模板
        view.setViewName("learing_article");
        //2.指定数据：调用service查询页面所需要的预览数据
        Map<String, Object> map = coursePubService.preview(courseBaseId);
        view.addAllObjects(map);
        return view;
    }

    //课程发布
    @PostMapping("/publish/{courseBaseId}")
    public ResponseResult publish(@PathVariable("courseBaseId") Long courseBaseId) throws Exception {
        return coursePubService.publish(courseBaseId);
    }

    //查询所有已发布课程
    @GetMapping("/findAll")
    public ResponseResult<List<CoursePubVo>> findAll() {
        //1.调用service查询所有已发布课程
        List<CoursePub> coursePubList = coursePubService.list();
        //2.转化成vo集合
        List<CoursePubVo> vos = BeanHelper.copyWithCollection(coursePubList, CoursePubVo.class);
        //3.返回
        return ResponseResult.okResult(vos);
    }

    //根据id查询已发布课程
    @GetMapping("{id}")
    public ResponseResult<CoursePubVo> findById(@PathVariable("id") Long id) {
        CoursePub coursePub = coursePubService.getById(id);
        CoursePubVo vo = BeanHelper.copyProperties(coursePub, CoursePubVo.class);
        return ResponseResult.okResult(vo);
    }



}
